<template>
  <basic-container>
    <el-container style="height: 500px; border: 1px solid #eee">
      <el-aside width="260px" style="border-right: 1px solid #eee">
        <el-input style="margin-bottom:10px;" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        <div class="box_btn">
          <!-- 根节点添加 -->
          <el-button type="text" icon="el-icon-plus" @click="addTree"></el-button>
        </div>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode"
          ref="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="title_left_span">{{ node.label }}</span>
            <span style="float: right;">
              <!-- 子节点添加 -->
              <el-button
                v-if="data.level !=3"
                type="text"
                style="margin-right:5px;padding:0;"
                icon="el-icon-circle-plus-outline"
                @click.stop="appendTree(data)"
              ></el-button>
              <el-button
                style="padding:0;"
                type="text"
                icon="el-icon-error"
                @click.stop="removeTree(data)"
              ></el-button>
            </span>
          </span>
        </el-tree>
      </el-aside>
      <el-container>
        <div class="text-center" style="min-width:500px;margin: 0 auto;">
          <h2 class="tree-title text-center">区域位置</h2>
          <!-- form -->
          <el-form :rules="rules" ref="ruleForm" :model="form" label-width="100px">
            <!-- 上级位置 -->
            <el-form-item style="text-align: left;" v-if="upShow" label="上级位置" prop="parentId">
              <el-cascader
                style="width:80%"
                :disabled="isShow"
                v-model="form.parentId"
                :options="treeData"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <!-- 行政区域 -->
            <el-form-item label="行政区域" prop="province">
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-select
                    :disabled="isShow"
                    placeholder="请选择省"
                    v-model="form.province"
                    @change="changeProvince"
                  >
                    <el-option
                      v-for="item in province"
                      :key="item.key"
                      :label="item.title"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7">
                  <el-select
                    :disabled="isShow"
                    placeholder="请选择市"
                    v-model="form.city"
                    @change="changeCity"
                  >
                    <el-option
                      v-for="item in city"
                      :key="item.key"
                      :label="item.title"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7">
                  <el-select :disabled="isShow" placeholder="请选择区" v-model="form.regionId">
                    <el-option
                      v-for="item in regionId"
                      :key="item.key"
                      :label="item.title"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- 小区名称 -->
            <el-form-item label="小区名称" prop="name">
              <el-input :disabled="addressShow" v-model="form.name" placeholder></el-input>
            </el-form-item>
            <!-- 地区层级 -->
            <!-- <el-form-item style=" text-align: left;" label="地区层级" prop="level">
              <el-select :disabled="isShow" placeholder="请选择层级" v-model="form.level">
                <el-option label="1级" :value="1"></el-option>
                <el-option label="2级" :value="2"></el-option>
                <el-option label="3级" :value="3"></el-option>
              </el-select>
            </el-form-item>-->
            <!-- 详细地址 -->
            <el-form-item v-if="detailedShow" label="详细地址" prop="address">
              <el-input :disabled="addressShow" v-model="form.address"></el-input>
            </el-form-item>
            <!-- btn -->
            <el-form-item class="form_item" v-if="!btnShow">
              <el-button @click="refresh" type="primary" size="small">更新</el-button>
            </el-form-item>
            <el-form-item class="form_item" v-if="btnShow">
              <el-button style="margin-right:20px;" @click="empty" type="primary" size="small">清空</el-button>
              <el-button @click="treeSubmit" type="primary" size="small">保存</el-button>
            </el-form-item>
            <!-- end -->
          </el-form>
        </div>
      </el-container>
    </el-container>
  </basic-container>
</template>

<script>
import {
  getTreeList,
  getTreeDetails,
  estateSave,
  estateUpdate,
  estateRemove,
  buildingRemove,
} from "@/api/meter/community";
import { getLazyTree } from "@/api/base/region";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      communityData: {},
      form1: {},
      form: {
        name: "", // 小区名称
        parentId: "0", // 上级地区
        province: "", // 省
        city: "", // 市
        regionId: "", // 区
        address: "", // 详细地址
        level: 1, // 层级
      },
      detailedShow: true,
      btnShow: true,
      status: "addTree",
      upShow: false,
      isShow: false,
      addressShow: false,
      value: "",
      filterText: "",
      treeData: [],
      defaultProps: {
        children: "child",
        label: "name",
      },
      treeForm: {
        regionId: "", // 上级位置
        // regionId:'', // 上级位置
        // regionId:'', // 上级位置
        // regionId:'', // 上级位置
        // regionId:'', // 上级位置
      },
      province: [],
      city: [],
      regionId: [],
      loading: true,
      data: [],
      props: {
        expandTrigger: "hover",
        children: "child",
        label: "name",
        value: "id",
        checkStrictly: true,
      },
      rules: {
        parentId: [
          { required: true, message: "请输入上级位置", trigger: "blur" },
        ],
        province: [
          { required: true, message: "请输入行政区域", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入小区名称", trigger: "blur" }],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.community_add, false),
        viewBtn: this.vaildData(this.permission.community_view, false),
        delBtn: this.vaildData(this.permission.community_delete, false),
        editBtn: this.vaildData(this.permission.community_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    getTreeList().then((res) => {
      this.treeData = res.data.data;
    });
    getLazyTree("00").then((res) => {
      this.province = res.data.data;
    });
  },
  methods: {
    treeSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let obj = this.form;
          if (
            Object.prototype.toString.call(this.form.parentId) ==
            "[object Array]"
          ) {
            this.form.parentId = this.form.parentId[
              this.form.parentId.length - 1
            ];
          }
          if (this.status == "refresh") {
            estateUpdate(obj).then((res) => {
              this.$notify({
                message: res.data.msg,
                type: "success",
              });
              this.empty();
              this.getTreeList();
            });
          } else {
            estateSave(obj).then((res) => {
              this.$notify({
                message: res.data.msg,
                type: "success",
              });
              this.empty();
              this.getTreeList();
            });
          }
        }
      });
    },
    // 左侧树加载
    getTreeList() {
      getTreeList().then((res) => {
        this.treeData = res.data.data;
      });
    },
    // 新增根节点
    addTree() {
      this.empty();
      this.upShow = false;
      this.btnShow = true;
      this.detailedShow = true;
      this.isShow = false;
      this.addressShow = false;
      this.status = "addTree";
      this.form.level = 1;
    },
    //新增下级
    async appendTree(data) {
      this.empty();
      this.upShow = true;
      this.detailedShow = true;
      this.btnShow = true;
      this.isShow = true;
      this.addressShow = false;
      this.status = "appendTree";
      this.communityData = data;
      // 参数转换
      this.form.parentId = data.id;
      await this.changeProvince(data.provinceCode);
      this.form.province = data.provinceCode;
      await this.changeCity(data.cityCode);
      this.form.city = data.cityCode;
      this.form.regionId = data.districtCode;
      if (data.level == 1) {
        this.form.level = 2;
      } else if (data.level == 2) {
        this.form.level = 3;
      }
    },
    // 更新按钮
    refresh() {
      if (this.form.level == 1) {
        this.btnShow = true;
        this.isShow = false;
        this.addressShow = false;
      } else {
        this.btnShow = true;
        this.isShow = true;
        this.addressShow = false;
      }
      this.detailedShow = true;
      this.status = "refresh";
    },
    // 点击左侧树
    async handleNodeClick(data) {
      this.empty();
      this.communityData = data;
      this.isShow = true;
      this.addressShow = true;
      this.btnShow = false;
      if (data.level == 1) {
        this.upShow = false;
      } else {
        this.upShow = true;
      }
      this.detailedShow = false;
      this.form = data;
      await this.changeProvince(data.provinceCode);
      this.form.province = data.provinceCode;
      await this.changeCity(data.cityCode);
      this.form.city = data.cityCode;
      this.form.regionId = data.districtCode;
    },
    // 删除按钮
    removeTree(val) {
      if (val.child && val.child.length > 0) {
        return this.$notify({
          title: "提示",
          message: "该地区下有下级地区,无法删除",
          type: "warning",
        });
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (val.level == 1) {
            return estateRemove(val.id);
          } else if (val.level == 2 || val.level == 3) {
            return buildingRemove(val.id);
          }
        })
        .then((res) => {
          this.$notify({
            message: res.data.msg,
            type: "success",
          });
          this.getTreeList();
        });
    },
    // 省级地区
    changeProvince(value) {
      this.city = [];
      this.regionId = [];
      this.form.city = "";
      this.form.regionId = "";
      getLazyTree(value).then((res) => {
        this.city = res.data.data;
      });
    },
    //市级地区
    changeCity(value) {
      this.regionId = [];
      this.form.regionId = "";
      getLazyTree(value).then((res) => {
        this.regionId = res.data.data;
      });
    },
    // 筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //校验提示清空
    clear() {
      this.$refs["ruleForm"].clearValidate();
    },
    // 清空
    empty() {
      this.form = {
        name: "", // 小区名称
        parentId: "0", // 上级地区
        province: "", // 省
        city: "", // 市
        regionId: "", // 区
        address: "", // 详细地址
        level: 1, // 层级
      };
      this.clear();
      // this.province = [];
      this.city = [];
      this.regionId = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-title {
  width: 100%;
}
.custom-tree-node {
  width: 100%;
  padding-right: 10px;
}
.box_btn {
  text-align: right;
  font-size: 16px;
  margin-right: 15px;
  // margin-bottom: 5px;
}
.form_item {
  text-align: center;
}
.title_left_span {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
